import {
	unified,
} from 'unified';
import {
	h,
} from 'hastscript';
import remarkParse from 'remark-parse';
import remarkFrontmatter from 'remark-frontmatter';
import remarkGfm from 'remark-gfm';
import remarkRehype from 'remark-rehype';
import rehypeRaw from 'rehype-raw';
import rehypeFormat from 'rehype-format';
import rehypeStringify from 'rehype-stringify';
import {
	visit,
} from 'unist-util-visit';

function remarkModifyPlugin({elementClassName, cssModules}){
	return function(tree, file){
		visit(tree, function(node){
			if(node.type === 'element'){
				if(cssModules.length){
					const className = elementClassName[node.tagName];
					if(className && typeof className === 'string'){
						node.properties[':class'] = `classes.${className}`;
					}
				}
			}
		});
	};
}

export default function(content){
	const options = this.getOptions();
	const {
		components,
		cssModules,
	} = options;
	const importList = Object.keys(components).map((name) => {
		return `import ${name} from '${components[name]}';`;
	}).concat(
		cssModules.length
			? [
				...cssModules.map((m,i) => `import classes${i} from '${m}';`),
				`const classes = Object.assign({}, ${cssModules.map((m,i) => `classes${i}`).join(', ')})`
			]
			: []
	).join('\n');
	const callback = this.async();
	const processor = unified()
		.use(remarkParse)
		.use(remarkFrontmatter)
		.use(remarkGfm)
		.use(remarkRehype, {allowDangerousHtml:true})
		.use(rehypeRaw)
		.use(rehypeFormat, {indent:'\t'})
		.use(remarkModifyPlugin, options)
		.use(rehypeStringify)
	;
	processor.process(content).then((file) => {
		const code = `
<template>
	<div>
		${String(file)}
	</div>
</template>

<script setup>
${importList}
</script>
		`;
		callback(null, code);
	}).catch(callback);
}